from typing import Dict
import yaml
import sys
import os

def write_yaml(r , path, method='w'):
    with open(path, method, encoding="utf-8") as f:
        yaml.dump(r,f)
        
def load_yaml(path):
    with open(path, 'r', encoding='utf-8') as f:
        # Loader=yaml.FullLoader
        result = yaml.safe_load(f.read())
        return result


def dynamic_import_variable():
    # 计算 config 目录的路径
    project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
    config_path = os.path.join(project_root, 'config')

    # 将 config 目录添加到 sys.path
    if config_path not in sys.path:
        sys.path.append(config_path)
    

def parse_example(result: Dict) -> Dict:
    sql_cmd_key = "sql_cmd"
    sql_result_key = "sql_result"
    table_info_key = "table_info"
    input_key = "input"
    final_answer_key = "answer"

    _example = {
        "input": result.get("query"),
    }

    steps = result.get("intermediate_steps")
    answer_key = sql_cmd_key # the first one
    for step in steps:
	    #这些步骤是成对的，一个字典（输入）后跟一个字符串（输出）。
		# 不幸的是没有模式，但你可以查看输入键
		# dict 看看输出应该是什么
        # The steps are in pairs, a dict (input) followed by a string (output).
        # Unfortunately there is no schema but you can look at the input key of the
        # dict to see what the output is supposed to be
        if isinstance(step, dict):
            # Grab the table info from input dicts in the intermediate steps once
            if table_info_key not in _example:
                _example[table_info_key] = step.get(table_info_key)

            if input_key in step:
                if step[input_key].endswith("SQLQuery:"):
                    answer_key = sql_cmd_key # this is the SQL generation input
                if step[input_key].endswith("Answer:"):
                    answer_key = final_answer_key # this is the final answer input
            elif sql_cmd_key in step:
                _example[sql_cmd_key] = step[sql_cmd_key]
                answer_key = sql_result_key # this is SQL execution input
        elif isinstance(step, str):
            # The preceding element should have set the answer_key
            _example[answer_key] = step
    return _example

